package kr.ac.mlb.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.ac.mlb.dao.ListDao;
import kr.ac.mlb.vo.ContentVo;

import org.json.simple.*;

@WebServlet("/JSon")
public class JsonServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		ListDao dao = new ListDao();
		List<ContentVo> list = dao.getList();

		int length = list.size();
		

		String jsonStr = "";
		response.setContentType("text/html; charset=utf-8");

		jsonStr += "{";
		jsonStr += "\"data\":[";

		for (int i = 0; i < length; i++) {
			jsonStr += "{";
			jsonStr += "\"content\":\"" + list.get(i).getContent() + "\",";
			jsonStr += "\"time\":\"" + list.get(i).getTime() + "\"";
			jsonStr += "}";		
			if (i < length - 1)
				jsonStr += ",";
		}
		jsonStr += "]";
		jsonStr += "}";
		
		PrintWriter out = response.getWriter();
		out.println(jsonStr);
	}

}
